/*
===========================================================================
Copyright (C) 2005 Sarunas

This file is part of MyPIRC source code.

DisksDB source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.

DisksDB source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with DisksDB; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
===========================================================================
*/
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;

namespace MyIRC
{
	public class Config
	{
		public Config(string fileName)
		{
			DataTable dt = new DataTable("Config");
			dt.Columns.Add("Key", typeof(string));
			dt.Columns.Add("Value", typeof(string));
			dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
			this.dsConfig.Tables.Add(dt);
		}

		public string GetValue(string key, string defaultValue)
		{
			DataRow dr = this.dsConfig.Tables[0].Rows.Find(key);

			if (null != dr)
			{
				return (string)dr[1];
			}
			else
			{
				dr = this.dsConfig.Tables[0].NewRow();
				dr[0] = key;
				dr[1] = defaultValue;
				this.dsConfig.Tables[0].Rows.Add(dr);

				return defaultValue;
			}
		}

		public int GetValue(string key, int defaultValue)
		{
			return int.Parse(GetValue(key, defaultValue.ToString()));
		}

		public bool GetValue(string key, bool defaultValue)
		{
			return bool.Parse(GetValue(key, defaultValue.ToString()));
		}

		public void SetValue(string key, string value)
		{
			DataRow dr = this.dsConfig.Tables[0].Rows.Find(key);

			if (null != dr)
			{
				dr[1] = value;
			}
			else
			{
				dr = this.dsConfig.Tables[0].NewRow();
				dr[0] = key;
				dr[1] = value;
				this.dsConfig.Tables[0].Rows.Add(dr);
			}
		}

		public void SetValue(string key, int value)
		{
			SetValue(key, value.ToString());
		}

		public void SetValue(string key, bool value)
		{
			SetValue(key, value.ToString());
		}

		protected void Load()
		{
			try
			{
				if (System.IO.File.Exists(this.fileName))
				{
					this.dsConfig.ReadXml(this.fileName);
				}
			}
			catch (Exception)
			{
				// using defaults
			}
		}

		protected void Save()
		{
			this.dsConfig.WriteXml(this.fileName);
		}

		protected DataSet dsConfig = new DataSet("Config");
		protected string fileName = null;
	}
}
